package com.hisense.ovcloud.common3.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

@Component
@Slf4j
@Lazy
@ConditionalOnClass(ConfigureRedisAction.class)
public class RedisDao {
    private final static String REDIS_NULL_VALUE = "REDIS_NULL_VALUE";
    private final ReactiveRedisTemplate<String, String> redisTemplate;

    public RedisDao(@Qualifier("stringReactiveRedisTemplate") ReactiveRedisTemplate<String, String> reactiveRedisTemplate) {
        this.redisTemplate = reactiveRedisTemplate;
    }

    public Mono<Boolean> set(String key, String value) {
        return redisTemplate.opsForValue().set(key, value);
    }

    public Mono<Boolean> set(String key, String value, int expireTimeInSeconds) {
        return redisTemplate.opsForValue().set(key, value, Duration.of(expireTimeInSeconds, ChronoUnit.SECONDS));
    }

    public Mono<Boolean> del(String key) {
        return redisTemplate.opsForValue().delete(key);
    }

    public Mono<Boolean> hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public Mono<String> get(String key) {
        return redisTemplate.opsForValue().get(key).defaultIfEmpty(REDIS_NULL_VALUE);
    }

    public Mono<Object> hget(String key, String field) {
        return redisTemplate.opsForHash().get(key, field);
    }

    public Mono<Boolean> hset(String key, String field, String value) {
        return redisTemplate.opsForHash().put(key, field, value);
    }

}
